package com.csb.config;

import com.csb.pojo.Permission;
import com.csb.pojo.Role;
import com.csb.pojo.UserInfo;
import com.csb.service.PermissionService;
import com.csb.service.RoleService;
import com.csb.service.UserService;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 负责认证用户身份和对用户进行授权
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    // 用户授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // System.out.println("已开启授权");
        // 获取用户信息
        UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 获取角色信息
        List<Role> roleList = roleService.findRoleByUserId(userInfo.getAccount());
        // 存放角色信息
        Set<String> roleSet = new HashSet<>();
        // 存放角色id
        List<Integer> roleIds = new ArrayList<>();
        // 遍历添加
        for (Role role : roleList) {
            roleSet.add(role.getRName());
            roleIds.add(role.getRId());
        }
        // 放入角色信息
        authorizationInfo.setRoles(roleSet);
        // 获取权限信息
        List<Permission> permissionList = permissionService.findByRoleId(roleIds.get(0));
        // 遍历权限信息
        Set<String> permissionSet = new HashSet<>();
        for (Permission permission : permissionList) {
            permissionSet.add(permission.getPermission());
        }
        // 添加权限
        authorizationInfo.setStringPermissions(permissionSet);
        // 测试输出
        return authorizationInfo;
    }

    // 用户认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
        // 令牌
        UsernamePasswordToken token = (UsernamePasswordToken) authToken;
        // 获取用户信息
        UserInfo user = userService.getUserInfoByAccount(token.getUsername());
        if (user == null) {
            return null;
        }
        // 创建认证  经账号放在shiro中
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPwd(), this.getName());
        // 返回
        return info;
    }
}
